package com.atguigu.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NIOClient {
    public static void main(String[] args) throws IOException {
        //1.得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();
        //2.设置非阻塞模式
        socketChannel.configureBlocking(false);
        //3.提供服务器的ip和端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
        //4.连接到服务器
        if(!socketChannel.connect(inetSocketAddress)){
            while(!socketChannel.finishConnect()){
                System.out.println("连接需要时间, 客户端不会阻塞，请等待...");
            }
        }
        //连接成功就发送数据
        String str = "hello, server.";
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        socketChannel.write(buffer);
        System.out.println("客户端发送数据成功...");
        socketChannel.close();
    }
}
